package testWeb;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import conn.Connection1;

/**
 * Servlet implementation class loginCheckServlet
 */
@WebServlet(description = "登录验证", urlPatterns = { "/loginCheckServlet" })
public class loginCheckServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public loginCheckServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Connection1 conn =new Connection1();
			com.mysql.jdbc.Connection connection = conn.getConnection();
			String username = new String(request.getParameter("username"));
			String pwd = new String(request.getParameter("password"));
			boolean flag = true ;
			// 获取Statement
			// 添加图书信息的SQL语句
			String sql = "select  * from user where name='"+ username + "'and password='" + pwd + "'";
			PreparedStatement ps = connection.prepareStatement(sql);
			// 执行查询
			ResultSet rs = ps.executeQuery(sql);// 执行SQL语句
			if(rs.next()){
				HttpSession session = request.getSession();
				session.setAttribute("username",username);
				session.setMaxInactiveInterval(5*60);
				response.sendRedirect("indexFront.jsp");
			}else{
				flag = false ; 
				request.setAttribute("flag",flag);
				request.getRequestDispatcher("login.jsp").forward(request,response);
			}
			// 关闭PreparedStatement，释放资源
			connection.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
